﻿using System;
using System.Linq;
using UnityEngine;
using Island;

class LoginHandler : IHandler
{
    public void RegisterHandler(HandlerCenter center)
    {
        center.AddHandler(Protocol.ReqLogin,OnLogin);
        center.AddHandler(Protocol.RspOtherLogin,OnOtherLogin);
        center.AddHandler(Protocol.RspAsycOthers,OnAsyncOthers);
        center.AddHandler(Protocol.RspLogoff,OnLogoff);
    }
    private void OnLogin(byte[] data)
    {
        PBAccount pb = Util.Deserilize<PBAccount>(data);

        //设置self的actor
        GameObject go = new GameObject("self");
        var actor = go.AddComponent<Actor>();

        ActorManager.Instance.LocalID = pb.id;
        ActorManager.Instance.AddActor(pb, actor);

        //玩家启动GPS
        actor.StartGPS();
        //UIManager.Instance.Open<UseInfoPanel>();
        Debug.Log("登录成功");
    }
    private void OnOtherLogin(byte[] data)
    {
        PBAccount acc = Util.Deserilize<PBAccount>(data);
        var actor = Util.CreateActor(acc.sex);
        actor.gameObject.SetActive(false);
        ActorManager.Instance.AddActor(acc, actor);
        
        //UIManager.Instance.GetPanel<UseInfoPanel>().UpdateTheUserData();
        Debug.Log("其他用户登录");
    }

    private void OnAsyncOthers(byte[] data)
    {
        PBAccounts accs = Util.Deserilize<PBAccounts>(data);
    
        foreach (var acc in accs.array)
        {
            var actor = Util.CreateActor(acc.sex);
            actor.gameObject.SetActive(false);
            ActorManager.Instance.AddActor(acc, actor);
            
            //ActorManager.Instance.AddAccount(acc);
        }
        //UIManager.Instance.GetPanel<UseInfoPanel>().UpdateTheUserData();
        Debug.Log("同步其他玩家");
    }

    private void OnLogoff(byte[] data)
    {
        PBAccount acc = Util.Deserilize<PBAccount>(data);

        var actor = ActorManager.Instance.GetActor(acc.id);
        GameObject.Destroy(actor.gameObject);

        ActorManager.Instance.RemoveActor(acc.id);
    }

}
